package com.myspring.dao.impl;

import com.myspring.dao.ProductDao;
import com.myspring.po.Product;
import com.myspring.utils.ConnectionFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * ClassName: ProductDaoImpl
 * Package: com.mystring.dao.impl
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/12/6 21:08
 * @Version 1.0
 */

@Repository
public class ProductDaoImpl implements ProductDao {
    /*交给Spring注入*/
    @Autowired
//    @Resource(name = "queryRunner")
//    @Resource
    private QueryRunner queryRunner;

    @Autowired
    ConnectionFactory connectionFactory;

    @Override
    public void updateProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),
                    "UPDATE spring.product SET pname=?,price=?,category=? WHERE pid=?",
                    product.getPname(),product.getPrice(),product.getCategory(),product.getPid());
//            int a = 1/0;
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
    }

    @Override
    public void saveProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),
                    "INSERT INTO spring.product(pname, price, category) VALUE (?,?,?)," +
                            product.getPname(),product.getPrice(),product.getCategory());
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
    }

    @Override
    public void deleteProduct(int id) {
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),
                    "DELETE FROM spring.product WHERE pid = ?",
                    id);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
    }

    @Override
    public List<Product> findAll() {
        try {
            return queryRunner.query("SELECT * FROM spring.product",
                    new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
